/**
 * @file       CIniFileParser.cpp
 * @brief      
 * @author     LiuJkun
 * @version    1.0.0
 */

/*********************************************************************
 *  LiuJikun   10/03/09      Initial Version
 *********************************************************************/

#include	<string.h>
#include	<algorithm>

#include	"CIniFileParser.h"

/**
 * @brief  constructor for class CIniFileParser
 */
//--------------------------------------------------------------------------------------
CIniFileParser::CIniFileParser ( )
{
}

/**
 * @brief 
 * @return
 */
bool CIniFileParser::parse ( const char *configFile )
{
#define	INI_FILE_LINE_MAX_LEN   100			//
    this->_m_configFile = configFile;
    this->_m_groups.clear();
    std::string group_name;
    char tmpBuf[INI_FILE_LINE_MAX_LEN + 1];
    std::ifstream ifs( this->_m_configFile.c_str() );
    if ( ! ifs ) {
        return false;
    } else {
        do {
            memset( tmpBuf, 0, INI_FILE_LINE_MAX_LEN + 1 );
            ifs.getline( tmpBuf, INI_FILE_LINE_MAX_LEN );
            if ( tmpBuf[0] == '\0'|| tmpBuf[0] == '#' ) {
                continue;
            }
            if ( tmpBuf[0] == '[' ) {
                group_name.clear();
                group_name.append( tmpBuf + 1, strlen(tmpBuf) - 2 );
//                printf ( "name = %s\n", group_name.c_str() );
            }
            if ( group_name.empty() ) { //any key value pair without in any group will be omitted.
                continue;
            }
            char *p = std::find( tmpBuf, tmpBuf + strlen(tmpBuf), INI_FILE_FIELD_SPLITTER );
            if ( p != tmpBuf + strlen(tmpBuf) ) {
                *p = '\0';
                this->_m_groups[ group_name ].insert( std::make_pair( tmpBuf, p + 1 ) );
                //this->_m_groups[tmpBuf] = p+1;
//                printf ( "key = %s, value = %s\n", tmpBuf, p+1 );
            }
        } while ( !ifs.eof() );				// -----  end do-while  -----
    }
    return true;
}		

/**
 * @brief 
 * @return
 */
KeyValueMap_t &CIniFileParser::operator [] ( const char *key )
{
    if ( this->_m_groups.find( key ) != this->_m_groups.end() ) {
        return this->_m_groups[key];
    } else {
        return this->_m_nullGroup;
    }
}		

